package com.akk.business;


import com.akk.PayConstants;
import com.akk.common.enums.AccessEnums;
import com.akk.common.enums.Enums;
import com.akk.common.enums.UserCardEnums;
import com.akk.exception.RestBusinessException;
import com.akk.module.access.entity.AccessBank;
import com.akk.module.access.entity.AccessBind;
import com.akk.module.access.service.AccessBankService;
import com.akk.module.app.service.AppService;
import com.akk.module.avs.entity.*;
import com.akk.module.avs.enums.AvsPayAccessEnums;
import com.akk.module.avs.enums.AvsPayHlbH5Enums;
import com.akk.module.avs.enums.AvsPayVipStatus;
import com.akk.module.avs.enums.AvsTransferStatus;
import com.akk.module.avs.model.request.*;
import com.akk.module.avs.model.response.AvsPayAccessRes;
import com.akk.module.avs.service.*;
import com.akk.module.hkpay.service.HkPayService;
import com.akk.module.hlbpay.model.*;
import com.akk.module.access.entity.Access;
import com.akk.module.access.service.AccessService;
import com.akk.module.hlbpay.service.Hlbh5Service;
import com.akk.module.hlbpay.util.Disguiser;
import com.akk.module.hlbpay.util.HlbBeanUtils;
import com.akk.module.hlbpay.service.HlbService;
import com.akk.utils.*;
import com.akk.utils.rsa.*;
import com.google.gson.Gson;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class AvsPayBusiness {

    @Autowired
    AvsPayOrderService avsPayOrderService;
    @Autowired
    AvsCustomerService avsCustomerService;
    @Autowired
    AccessService accessService;
    @Autowired
    AppService appService;
    @Autowired
    AvsPayAccessService avsPayAccessService;
    @Autowired
    HlbService hlbService;

    @Autowired
    AvsPayCashBindService avsPayCashBindService;

    @Autowired
    private AvsPayVipService avsPayVipService;

    @Autowired
    private AvsPayVipConfigService avsPayVipConfigService;

    @Autowired
    private AccessBankService bankService;

    @Autowired
    private AvsHlbQuickBusiness hlbQuickBusiness;

    @Autowired
    private AvsHkPayBusiness hkPayBusiness;

    @Autowired
    private Hlbh5Service hlbh5Service;

    @Autowired
    private AvsYbPayBusiness ybPayBusiness;

    @Value("${server.url}")
    private String serverUrl;

    @Value("${temp.path}")
    private String path;

    @Autowired
    private AvsHxtPayBusiness hxtPayBusiness;

    public RestResponse showPayAccess() {
        List<AvsPayAccessRes> payAccessRes = avsPayAccessService.accessList();
        return RestResponse.build(payAccessRes);
    }

    // 创建订单
    @Transactional
    public RestResponse createPayOrder(CreatePayOrderRequest request) {
        if (request.getOrderType().equals("vip")) {
            List<AvsPayVipConfig> configs = avsPayVipConfigService.selectAll();
            if (configs.size() == 0)
                return RestResponse.build(RestResponse.AVS_ERROR_CODE, "配置信息尚未初始化");
            AvsPayVipConfig config = configs.get(0);
            if (config.getDiscountEndDate().compareTo(new Date()) < 0)
                request.setAmount(config.getVipMoney().toString());
            else
                request.setAmount((config.getVipDiscount() <= 0 ? config.getVipMoney() : config.getVipDiscount()).toString());
            request.setRemark(PayConstants.VIP_CASH);
        } else {
            List<AvsPayVip> vips = avsPayVipService.findByUserId(request.getPayerId());
            if (vips.size() == 0)
                return RestResponse.build(RestResponse.AVS_ERROR_CODE, "用户信息错误");
            AvsPayVip payVip = vips.get(0);
            if (payVip.getStatus() == AvsPayVipStatus.VipStatus.NORMAL.getValue())
                return RestResponse.build(RestResponse.AVS_ERROR_CODE, "请先缴费成为VIP");
            else if (payVip.getStatus() == AvsPayVipStatus.VipStatus.BLACK.getValue())
                return RestResponse.build(RestResponse.AVS_ERROR_CODE, "您已被拉入黑名单，请联系客服处理。");
            else if (payVip.getEndTime().compareTo(new Date()) < 0)
                return RestResponse.build("20016", "您的VIP已经到期，请续费后使用");
        }
        AvsPayAccess payAccess = avsPayAccessService.queryById(request.getGatewayId());
        if (payAccess == null)
            return RestResponse.build(RestResponse.AVS_ERROR_CODE, "支付环境异常");
        if (Double.valueOf(request.getAmount()) > payAccess.getSingleTime()) {
            return RestResponse.build(RestResponse.AVS_ERROR_CODE, "单笔限额" + payAccess.getSingleTime());
        }
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        int hour = calendar.get(Calendar.HOUR_OF_DAY);
        if (hour < payAccess.getTransStart() || hour >= payAccess.getTransEnd()) {
            return RestResponse.build(RestResponse.AVS_ERROR_CODE, "此通道开始时间为" + payAccess.getTransStart() + "时-" + payAccess.getTransEnd() + "时");
        }
        Access access = accessService.findByAccessId(payAccess.getAccessId());
        if (access == null) {
            return RestResponse.build(RestResponse.AVS_ERROR_CODE, "支付环境异常");
        }

        AvsCustomer avsCustomer = avsCustomerService.findByCustomerId(request.getPayerId());
        if (avsCustomer == null)
            return RestResponse.build(RestResponse.AVS_ERROR_CODE, "用户信息不存在");
        // 微信 4、5
        // 内测
        String merIds = "M1612160092002#M1703090095183#M1612180092005#M1612190092009#M1612270092016#" +
                "M1703080094874#M1707310117553";
        if (!merIds.contains(avsCustomer.getUniqueId())
                && ("9".equals(access.getAccessId()))) {
            return RestResponse.build(RestResponse.AVS_ERROR_CODE, "此通道内测中，暂未开放。敬请期待。");
        }

        if ((payAccess.getPayStatus() != 1 || access.getAccessStatus() != 1)
                && !merIds.contains(avsCustomer.getUniqueId())) {
            return RestResponse.build(RestResponse.AVS_ERROR_CODE, "通道维护中，暂不可用");
        }
        if (access.getAccessGateway().equals(AvsPayAccessEnums.PayAccess.HK_PAY.getValue()) && !request.getRemark().equals(PayConstants.VIP_CASH)) {
            return RestResponse.build(RestResponse.AVS_ERROR_CODE, "此通道收款功能处理中，暂未开放");
        }
        if (payAccess.getMinMoney() > Double.valueOf(request.getAmount()))
            return RestResponse.build(RestResponse.AVS_ERROR_CODE, "通道最低刷卡金额" + payAccess.getMinMoney() + "元");
        DecimalFormat df = new DecimalFormat("0.00");
        df.setRoundingMode(RoundingMode.HALF_UP);

        // 手续费
        Double serviceCost = Double.valueOf(request.getAmount()) * payAccess.getRate() * 0.01 + payAccess.getDeposit();
        if (serviceCost < 0)
            serviceCost = 0.0;
        serviceCost = Double.valueOf(df.format(serviceCost));
        // 实际到账
        Double realAmount = Double.valueOf(request.getAmount()) - serviceCost;
        // 通道成本
        Double gatewayCost = Double.valueOf(df.format(Double.valueOf(request.getAmount()) * payAccess.getGatewayCost() * 0.01));
        // 清算费用
        Double clearMoney = Double.valueOf(df.format(realAmount * payAccess.getClearRate() * 0.01 + payAccess.getClearMoney()));
        // 利润
        Double profit = serviceCost - gatewayCost - clearMoney;


        // VIP缴费
        if (request.getRemark().equals(PayConstants.VIP_CASH)) {
            serviceCost = 0.0;
            realAmount = Double.valueOf(request.getAmount());
            profit = Double.valueOf(df.format(Double.valueOf(request.getAmount()) - Double.valueOf(request.getAmount()) * payAccess.getGatewayCost() * 0.01));
        }
        if (access.getAccessGateway().equals("hxtpay") && request.getRemark().equals(PayConstants.VIP_CASH)) {
            return RestResponse.build(RestResponse.AVS_ERROR_CODE, "此通道不可用于VIP缴费");
        }

        if (realAmount <= 0)
            return RestResponse.build(RestResponse.AVS_ERROR_CODE, "刷卡金额过低");

        appService.findByAppId(avsCustomer.getAppId());
        AvsPayOrder order = new AvsPayOrder();
        order.setOrderId(IDUtils.getPK());
        order.setOrderNum(IDUtils.getUniqueNum14());
        order.setAppId(request.getAppId());
        order.setGatewayCost(gatewayCost);
        order.setProfit(profit);
        order.setAccessId(access.getAccessId());
        order.setAmountTotal(Double.parseDouble(request.getAmount()));
        order.setCount(1);
        order.setRealAmount(realAmount);
        order.setRemark(request.getRemark());
        order.setServiceCost(serviceCost);
        order.setPayerId(request.getPayerId());
        order.setCreateDate(new Date());
        order.setStatus(Enums.OrderStatusEnum.NO_PAYED.getValue());
        order.setOrderIp(request.getOrderIp());
        avsPayOrderService.save(order);
        Map<String, Object> result = new HashMap<>();
        result.put("orderNum", order.getOrderNum());
        result.put("gateway", access.getAccessGateway());
        result.put("payerId", request.getPayerId());
        if (Integer.valueOf(request.getPayType()).intValue() == AccessEnums.TypeEnum.QUICK_URL.getValue()) {
            result.put("URL", access.getQuickUrl() != null ? access.getQuickUrl() : access.getCodeUrl());
        }
        if (Integer.valueOf(request.getPayType()).intValue() == AccessEnums.TypeEnum.CODE_URL.getValue()) {
            result.put("URL", access.getCodeUrl() != null ? access.getCodeUrl() : access.getQuickUrl());
        }
        return RestResponse.build(result);
    }

    // 通道列表
    public RestResponse accessBankList() {
        return RestResponse.build(accessService.selectAllBank());
    }

    // 获取绑定卡
    public RestResponse getPayerBind(String gateway, String payerId, String orderNum) {
        List<Access> accessList = accessService.findByGateway(gateway);
        if (accessList.isEmpty()) {
            return RestResponse.build(RestResponse.AVS_ERROR_CODE, "支付环境异常");
        }
        Access access = accessList.get(0);
        if (access == null) {
            throw new RestBusinessException("通道不能为空");
        }
        AvsPayOrder order = avsPayOrderService.findByOrderNum(orderNum).get(0);
        Map<String, Object> result = new HashMap<>();
        result.put("order", order);
        result.put("payerBind", accessService.findAccessBindByPayerIdAndAccessId(payerId, access.getAccessId()));
        return RestResponse.build(result);
    }


    // 结算卡列表
    public RestResponse depositCardList(String payerId) {
        return RestResponse.build(avsPayCashBindService.findByPayerId(payerId));
    }

    // 添加结算卡
    @Transactional
    public RestResponse addDepositCard(AddDepositCardRequest request, BindingResult result) {
        if (result.hasErrors())
            return RestResponse.build(RestResponse.AVS_ERROR_CODE, result.getFieldError().getDefaultMessage());
        AvsCustomer customer = avsCustomerService.findByCustomerId(request.getPayerId());
        if (customer == null)
            return RestResponse.build(RestResponse.AVS_ERROR_CODE, "信息有误");
        if (request.getHoldName().equals("null") || request.getHoldName().equals("")) {
            return RestResponse.build(RestResponse.AVS_ERROR_CODE, "持卡人姓名不能为空。");
        }
        request.setHoldName(customer.getCustomerName());
        request.setIdCard(customer.getIdCard());
        List<AvsPayCashBind> avsPayCardBinds = avsPayCashBindService.findByPayerId(request.getPayerId());
        List<AvsPayCashBind> deposits = avsPayCashBindService.findByIsDepositAndPayerId(1, request.getPayerId());
        String[] card = request.getBankName().split("##");
        AvsPayCashBind avsPayCardBind = new AvsPayCashBind();
        avsPayCardBind.setCashBindId(IDUtils.getPK());
        avsPayCardBind.setPayerId(request.getPayerId());
        avsPayCardBind.setPhone(request.getPhone());
        avsPayCardBind.setBankName(card[1]);
        avsPayCardBind.setCardNum(request.getCardNum());
        avsPayCardBind.setCardType(request.getCardType());
        avsPayCardBind.setHoldName(request.getHoldName());
        avsPayCardBind.setIdCard(request.getIdCard());
        avsPayCardBind.setPhone(request.getPhone());
        avsPayCardBind.setCreateDate(new Date());
        avsPayCardBind.setUpdateDate(new Date());
        avsPayCardBind.setLastFourNum(request.getCardNum().substring(request.getCardNum().length() - 4, request.getCardNum().length()));
        avsPayCardBind.setIsDeposit(0);
        if (!avsPayCardBinds.isEmpty()) {
            for (AvsPayCashBind CardBind : avsPayCardBinds) {
                if (CardBind.getCardNum().equals(request.getCardNum())) {
                    return RestResponse.build(RestResponse.AVS_ERROR_CODE, "卡包中已存在该卡");
                }
            }
        } else {
            if (request.getCardType().equals("J") && deposits.size() == 0)
                avsPayCardBind.setIsDeposit(1);
            else
                avsPayCardBind.setIsDeposit(0);
        }
        avsPayCashBindService.save(avsPayCardBind);

        Map params = new HashMap();
        params.put("cardNum", request.getCardNum());
        params.put("payerId", request.getPayerId());
        List<AccessBind> accessBinds = accessService.findByParams(params);
        if (accessBinds.size() > 0)
            return RestResponse.build("银行卡添加成功");
        AccessBind accessBind = new AccessBind();
        accessBind.setAccessBindId(IDUtils.getPK());
        accessBind.setCardNum(request.getCardNum());
        accessBind.setCardName(card[1]);
        accessBind.setLastFourNum(request.getCardNum().substring(request.getCardNum().length() - 4, request.getCardNum().length()));
        accessBind.setPhone(request.getPhone());
        accessBind.setAccessId("1");
//        RSAUtils.encryptedDataOnJava()
        accessBind.setCvv2(request.getCvv2());
        accessBind.setCardCode(card[0]);
        accessBind.setValidity(request.getValidity());
        accessBind.setCardType(request.getCardType());
        accessBind.setPayerId(request.getPayerId());
        accessBind.setHoldName(customer.getCustomerName());
        accessService.save(accessBind);

        return RestResponse.build("银行卡添加成功");
    }

    /// 删除结算卡
    @Transactional
    public RestResponse delDepositCard(String cashBindId, String payerId) {
        List<AvsPayCashBind> cashBinds = avsPayCashBindService.findByCashBinIdAndPayerId(cashBindId, payerId);
        if (cashBinds.isEmpty()) {
            return RestResponse.build(RestResponse.AVS_ERROR_CODE, "未查询到该卡信息");
        }
        if (cashBinds.get(0).getIsDeposit() == 1) {
            return RestResponse.build(RestResponse.AVS_ERROR_CODE, "请先解除提现卡绑定");
        } else {
            accessService.deleteBind(payerId, cashBinds.get(0).getCardNum());
            avsPayCashBindService.deleteByCashBindId(cashBindId);
            return RestResponse.build("删除成功");
        }
    }

    // 查询用户绑定卡
    public RestResponse queryUserBindCard(String payerId){
        return hlbService.queryUserBindCard(payerId);
    }

    // 设置结算卡
    @Transactional
    public RestResponse setCashCard(String cashBindId, String payerId) {
        List<AvsPayCashBind> cashBinds = avsPayCashBindService.findByCashBinIdAndPayerId(cashBindId, payerId);
        if (cashBinds.isEmpty()) {
            return RestResponse.build(RestResponse.AVS_ERROR_CODE, "未查询到该卡信息");
        }
        if (cashBinds.get(0).getCardType().equals("X"))
            return RestResponse.build(RestResponse.AVS_ERROR_CODE, "信用卡不能设置为结算卡");
        if (cashBinds.get(0).getIsDeposit() == 1) {
            return RestResponse.build(RestResponse.AVS_ERROR_CODE, "操作无效");
        } else {
//            List<AvsPayCashBind> cashBindIsDepositList = avsPayCashBindService.findByIsDepositAndPayerId(1,payerId);
//            AvsPayCashBind cashBindIsDeposit = cashBindIsDepositList.get(0);
//            cashBindIsDeposit.setIsDeposit(0);
//            cashBindIsDeposit.setUpdateDate(new Date());
            AvsPayCashBind cashBind = cashBinds.get(0);
            cashBind.setUpdateDate(new Date());
            cashBind.setIsDeposit(1);
            avsPayCashBindService.resetDeposit(payerId);
//            avsPayCashBindService.update(cashBindIsDeposit);
            avsPayCashBindService.update(cashBind);
            return RestResponse.build("结算卡修改成功");
        }
    }

    // 获取支付通道
    public RestResponse getQuickAccess(AvsCustomerRequest request) {
        AvsCustomer avsCustomer = avsCustomerService.findByCustomerId(request.getCustomerId());
        if (avsCustomer == null) {
            return RestResponse.build(RestResponse.AVS_ERROR_CODE, "系统错误，请稍后再试");
        }
        return RestResponse.build(avsPayAccessService.payAccessRestList());
    }

    // 获取订单列表
    public RestResponse getOrderRecord(String playerId, String appId) {
        if (StringUtils.isEmpty(playerId) || StringUtils.isEmpty(appId))
            return RestResponse.build(RestResponse.AVS_ERROR_CODE, "环境异常");
        return RestResponse.build(avsPayOrderService.findByPayerIdAndAppId(playerId, appId));
    }

    // 获取订单记录详情
    public RestResponse getOrderRecordInfo(String orderId) {
        AvsPayOrder order = avsPayOrderService.findByOrderId(orderId);
        if (order != null) {
            order.setPayCardNo(StringUtils.isEmpty(order.getPayCardNo()) ? "" : order.getPayCardNo().substring(0, 4) + "******" + order.getPayCardNo().substring(order.getPayCardNo().length() - 4, order.getPayCardNo().length()));
            order.setCashCardNo(StringUtils.isEmpty(order.getCashCardNo()) ? "" : order.getCashCardNo().substring(0, 4) + "******" + order.getCashCardNo().substring(order.getCashCardNo().length() - 4, order.getCashCardNo().length()));
        }
        return RestResponse.build(order);
    }

    // 获取用户名
    public RestResponse getUserName(String payerId) {
        AvsCustomer customer = avsCustomerService.findByCustomerId(payerId);
        if (customer == null)
            return RestResponse.build(RestResponse.AVS_ERROR_CODE, "用户信息不存在");
        return RestResponse.build(customer.getCustomerName());
    }


    // 获取用户VIP信息
    public RestResponse getUserVipInfo(String userId) {
        List<AvsPayVip> vips = avsPayVipService.findByUserId(userId);
        AvsPayVip avsPayVip;
        if (vips.size() == 0) {
            AvsCustomer customer = avsCustomerService.findByCustomerId(userId);
            if (customer == null)
                return RestResponse.build(RestResponse.AVS_ERROR_CODE, "用户信息不存在");
            avsPayVip = new AvsPayVip();
            avsPayVip.setVipId(IDUtils.getPK());
            avsPayVip.setCreateTime(new Date());
            avsPayVip.setStatus(AvsPayVipStatus.VipStatus.NORMAL.getValue());
            avsPayVip.setIsDraw(AvsPayVipStatus.DrawStatus.NO.getValue());
            avsPayVip.setMoney(0.0);
            avsPayVip.setUserId(userId);
            avsPayVipService.insert(avsPayVip);
        } else {
            avsPayVip = vips.get(0);
        }
        return RestResponse.build(avsPayVip);
    }


    // 获取用户已支付金额
    public RestResponse getPayCount(String payerId) {
        Double count = avsPayOrderService.payCount(payerId);
        return RestResponse.build(count);
    }

    // 获取配置信息
    public RestResponse getVipConfig() {
        List<AvsPayVipConfig> configs = avsPayVipConfigService.selectAll();
        if (configs.size() == 0)
            return RestResponse.build(RestResponse.AVS_ERROR_CODE, "配置尚未初始化");
        AvsPayVipConfig config = configs.get(0);
        config.setSettleAccess(null);
        return RestResponse.build(config);
    }

    // VIP奖励提现
    public RestResponse getVipReward(AvsPayVipRewardRequest request, HttpServletRequest servletRequest) {
        if (StringUtils.isEmpty(request.getOrderIp())) {
            request.setOrderIp(IPUtil.getIpAddress(servletRequest));
        }
        List<AvsPayVip> payVips = avsPayVipService.findByUserId(request.getPayerId());
        if (payVips.size() == 0)
            return RestResponse.build(RestResponse.AVS_ERROR_CODE, "用户状态错误，请联系客服");
        AvsPayVip payVip = payVips.get(0);
        if (payVip.getStatus() == AvsPayVipStatus.VipStatus.NORMAL.getValue())
            return RestResponse.build(RestResponse.AVS_ERROR_CODE, "仅VIP用户可用");
        else if (payVip.getStatus() == AvsPayVipStatus.VipStatus.BLACK.getValue())
            return RestResponse.build(RestResponse.AVS_ERROR_CODE, "您已被拉入黑名单，请联系客服处理");
        if (payVip.getIsDraw() == AvsPayVipStatus.DrawStatus.YES.getValue())
            return RestResponse.build(RestResponse.AVS_ERROR_CODE, "您已经提现过了");
        Double countMoney = avsPayOrderService.payCount(request.getPayerId());
        List<AvsPayVipConfig> configs = avsPayVipConfigService.selectAll();
        if (configs.size() == 0)
            return RestResponse.build(RestResponse.AVS_ERROR_CODE, "配置尚未初始化，请稍后再试");
        AvsPayVipConfig config = configs.get(0);
        if (countMoney < config.getCountBack())
            return RestResponse.build(RestResponse.AVS_ERROR_CODE, "您的刷卡金额尚未达到" + config.getCountBack());
        if (config.getBackEndDate().compareTo(new Date()) < 0) {
            return RestResponse.build(RestResponse.AVS_ERROR_CODE, "返现活动已经结束。");
        }
        AvsPayAccess avsPayAccess = avsPayAccessService.queryById(config.getSettleAccess());
        if (avsPayAccess == null || avsPayAccess.getPayStatus() == 0)
            return RestResponse.build(RestResponse.AVS_ERROR_CODE, "提现通道异常，请稍后再试。");
        DecimalFormat df = new DecimalFormat("0.00");
        df.setRoundingMode(RoundingMode.HALF_UP);
        // 利润
        Double profit = Double.valueOf(df.format(config.getBackMoney() + config.getBackMoney() * avsPayAccess.getClearRate() * 0.01 + avsPayAccess.getClearMoney()));
        AvsPayOrder order = new AvsPayOrder();
        order.setAccessId(avsPayAccess.getAccessId());
        order.setAmountTotal(config.getBackMoney());
        order.setRealAmount(config.getBackMoney());
        order.setCreateDate(new Date());
        order.setServiceCost(0.0);
        order.setOrderId(IDUtils.getPK());
        order.setOrderNum(IDUtils.getUniqueNum14());
        order.setCount(1);
        order.setProfit(profit * -1);
        order.setGatewayCost(0.0);
        order.setAppId(request.getAppId());
        order.setRemark(PayConstants.VIP_REWARD);
        order.setPayerId(request.getPayerId());
        order.setOrderIp(request.getOrderIp());
        order.setStatus(Enums.OrderStatusEnum.DOING.getValue());
        avsPayOrderService.save(order);
        DepositRequest depositRequest = new DepositRequest();
        depositRequest.setAmount(order.getRealAmount().toString());
        depositRequest.setOrderNum(order.getOrderNum());
        depositRequest.setPayerId(order.getPayerId());
        depositRequest.setSummary(order.getRemark());
        RestResponse restResponse = deposit(depositRequest);
        if (restResponse.getCode().equals("200")) {
            payVip.setIsDraw(AvsPayVipStatus.DrawStatus.YES.getValue());
            avsPayVipService.update(payVip);
            order.setStatus(Enums.OrderStatusEnum.SUCCESS_REWAARD.getValue());
            order = avsPayOrderService.findByOrderId(order.getOrderId());
            avsPayOrderService.update(order);
            restResponse = RestResponse.build("提现成功");
        }
        return restResponse;
    }


    // 获取所有绑定卡
    public RestResponse getPayerAllBind(String payerId, String gateway) {
        return RestResponse.build(accessService.findByPayerIdAndGateway(payerId, gateway));
    }

    // 支付状态
    public RestResponse payStatus() {
        return RestResponse.build("success");
    }

    // 订单查询
    public RestResponse transferQuery(String orderNum) {
        if (StringUtils.isEmpty(orderNum)) {
            return RestResponse.build(RestResponse.AVS_ERROR_CODE, "订单号有误");
        }
        List<AvsPayOrder> orders = avsPayOrderService.findByOrderNum(orderNum);
        if (orders.isEmpty())
            return RestResponse.build(RestResponse.AVS_ERROR_CODE, "订单信息不存在");
        AvsPayOrder order = orders.get(0);
        Access access = accessService.findByAccessId(order.getAccessId());
        if (access.getAccessGateway().equals(AvsPayAccessEnums.PayAccess.HXT_PAY.getValue())) {
            // 恒信通
            return hxtPayBusiness.transferQuery(order);
        } else if (access.getAccessGateway().equals(AvsPayAccessEnums.PayAccess.HLB_H5_PAY.getValue())) {
            // 合力宝h5
            return hlbService.transferQueryHandler(order);
        } else if (access.getAccessGateway().equals(AvsPayAccessEnums.PayAccess.HLB_QUICK_PAY.getValue())) {
            // 合力宝快捷
            return hlbService.transferQueryHandler(order);
        } else if (access.getAccessGateway().equals(AvsPayAccessEnums.PayAccess.HK_PAY.getValue())) {
            // 汇卡
            return hkPayBusiness.orderQuery(order);
        } else if (access.getAccessGateway().equals(AvsPayAccessEnums.PayAccess.YB_PAY.getValue())) {
            // 易宝
            return ybPayBusiness.transferQuery(order);
        }
        return RestResponse.build(RestResponse.AVS_ERROR_CODE, "查询失败");
    }

    // 刷卡结算进度
    public RestResponse depositProgress(String orderNum) {
        List<AvsPayOrder> orders = avsPayOrderService.findByOrderNum(orderNum);
        if (orders.isEmpty())
            return RestResponse.build(RestResponse.AVS_ERROR_CODE, "订单信息不存在");
        AvsPayOrder order = orders.get(0);
        Access access = accessService.findByAccessId(order.getAccessId());
        if (access.getAccessGateway().equals(AvsPayAccessEnums.PayAccess.HXT_PAY.getValue())) {
            // 恒信通
            return hxtPayBusiness.depositProgress(order);
        } else if (access.getAccessGateway().equals(AvsPayAccessEnums.PayAccess.HLB_H5_PAY.getValue())) {
            // 合力宝h5
            return hlbService.depositProgress(order);
        } else if (access.getAccessGateway().equals(AvsPayAccessEnums.PayAccess.HLB_QUICK_PAY.getValue())) {
            // 合力宝快捷
            return hlbService.depositProgress(order);
        } else if (access.getAccessGateway().equals(AvsPayAccessEnums.PayAccess.HK_PAY.getValue())) {
            // 汇卡
            return hkPayBusiness.depositProgress(order);
        }
        return RestResponse.build(RestResponse.AVS_ERROR_CODE, "查询失败");
    }

    // 删除订单
    public RestResponse deleteOrder(String orderId, String payerId) {
        AvsPayOrder order = avsPayOrderService.findByOrderId(orderId);
        if (order == null || !Objects.equals(order.getStatus(), Enums.OrderStatusEnum.NO_PAYED.getValue())) {
            return RestResponse.build(RestResponse.AVS_ERROR_CODE, "此订单状态不可删除");
        } else if (!Objects.equals(order.getPayerId(), payerId)) {
            return RestResponse.build(RestResponse.AVS_ERROR_CODE, "非法请求");
        }
        avsPayOrderService.deleteByOrderId(orderId);
        return RestResponse.build("success");
    }

    public RestResponse accessBankListByIndex() {
        return RestResponse.build(bankService.queryBankByIndex());
    }

    // 提现
    public RestResponse deposit(DepositRequest request) {
        // 从配置读取提现通道
//        List<AvsPayVipConfig> configs = avsPayVipConfigService.selectAll();
//        if (configs.isEmpty())
//            return RestResponse.build(RestResponse.AVS_ERROR_CODE,"提现通道尚未配置");
//        AvsPayVipConfig config = configs.get(0);
//        AvsPayAccess payAccess = avsPayAccessService.queryById(config.getSettleAccess());
//        if (payAccess == null || payAccess.getPayStatus() == 0){
//            return RestResponse.build(RestResponse.AVS_ERROR_CODE,"提现通道不可用");
//        }
//        Access access = accessService.findByAccessId(payAccess.getAccessId());
//        if (access == null || access.getAccessStatus() == 0){
//            return RestResponse.build(RestResponse.AVS_ERROR_CODE,"提现通道不可用");
//        }

        // 根据订单通道提现
        List<AvsPayOrder> orders = avsPayOrderService.findByOrderNum(request.getOrderNum());
        if (orders.isEmpty())
            return RestResponse.build(RestResponse.AVS_ERROR_CODE, "订单信息不存在");
        AvsPayOrder order = orders.get(0);
        if (!order.getPayerId().equals(request.getPayerId()))
            return RestResponse.build(RestResponse.AVS_ERROR_CODE, "用户信息不正确");
        if (request.getIsRedeposit() == 1) {
            // 重新发起提现
            order.setIsRedeposit(request.getIsRedeposit());
            order.setRedepositDate(new Date());
            avsPayOrderService.update(order);
        }
//        AvsPayAccess payAccess = avsPayAccessService.queryById(order.getAccessId());
//        if (payAccess == null || payAccess.getPayStatus() == 0) {
//            return RestResponse.build(RestResponse.AVS_ERROR_CODE, "提现通道不可用");
//        }
        Access access = accessService.findByAccessId(order.getAccessId());
        if (access == null || access.getAccessStatus() == 0) {
            return RestResponse.build(RestResponse.AVS_ERROR_CODE, "提现通道不可用");
        }
        RestResponse restResponse = null;
        if (access.getAccessGateway().equals(AvsPayAccessEnums.PayAccess.HK_PAY.getValue())) {
            // 汇卡提现
            restResponse = hkPayBusiness.withdrawalToMer(order.getOrderNum(), order.getPayerId());
        } else if (access.getAccessGateway().equals(AvsPayAccessEnums.PayAccess.HLB_H5_PAY.getValue())
                || access.getAccessGateway().equals(AvsPayAccessEnums.PayAccess.HLB_QUICK_PAY.getValue())) {
            // 合利宝提现
            restResponse = hlbQuickBusiness.deposit(request);
        } else if (access.getAccessGateway().equals(AvsPayAccessEnums.PayAccess.HXT_PAY.getValue())) {
            // 恒信通提现
            restResponse = RestResponse.build(RestResponse.AVS_ERROR_CODE, "此通道暂不支手动持提现");
        } else if (access.getAccessGateway().equals(AvsPayAccessEnums.PayAccess.YB_PAY.getValue())) {
            // 易宝
            restResponse = ybPayBusiness.withDrawApi(order.getOrderNum(), request.getPayerId());
        } else if (access.getAccessGateway().equals(AvsPayAccessEnums.PayAccess.CJ_PAY.getValue())) {
            // 畅捷
            restResponse = RestResponse.build(RestResponse.AVS_ERROR_CODE, "此通道暂不支手动持提现");
        }
        return restResponse;
    }

    // 创建VIP缴费订单
    public RestResponse createVipPayOrder(CreatePayOrderRequest request) {
        AvsCustomer customer = avsCustomerService.findByCustomerId(request.getPayerId());
        if (customer == null)
            return RestResponse.build(RestResponse.AVS_ERROR_CODE, "用户信息不存在");
        List<AvsPayVipConfig> configs = avsPayVipConfigService.selectAll();
        if (configs.isEmpty())
            return RestResponse.build(RestResponse.AVS_ERROR_CODE, "配置尚未初始化");
        AvsPayVipConfig config = configs.get(0);
        AvsPayAccess payAccess = avsPayAccessService.queryById(config.getVipAccess());
        if (payAccess == null)
            return RestResponse.build(RestResponse.AVS_ERROR_CODE, "通道信息有误");
        else if (payAccess.getPayStatus().intValue() != 1)
            return RestResponse.build(RestResponse.AVS_ERROR_CODE, "缴费通道暂不可用");
        Access access = accessService.findByAccessId(payAccess.getAccessId());
        if (access.getAccessStatus().intValue() != 1)
            return RestResponse.build(RestResponse.AVS_ERROR_CODE, "缴费通道暂不可用");
        AvsPayOrder order = new AvsPayOrder();
        order.setRemark(PayConstants.VIP_CASH);
        if (config.getDiscountEndDate().compareTo(new Date()) > 0) {
            order.setAmountTotal(config.getVipDiscount());
            order.setRealAmount(config.getVipDiscount());
        } else {
            order.setAmountTotal(config.getVipMoney());
            order.setRealAmount(config.getVipMoney());
        }
        DecimalFormat df = new DecimalFormat("0.00");
        df.setRoundingMode(RoundingMode.HALF_UP);
        // 通道成本
        Double gatewayCost = Double.valueOf(df.format(order.getRealAmount() * payAccess.getGatewayCost() * 0.01));
        // 利润
        Double profit = Double.valueOf(df.format(order.getRealAmount() - order.getRealAmount() * payAccess.getGatewayCost() * 0.01));
        order.setOrderId(IDUtils.getPK());
        order.setOrderNum(IDUtils.getUniqueNum14());
        order.setAppId(request.getAppId());
        order.setGatewayCost(gatewayCost);
        order.setProfit(profit);
        order.setAccessId(payAccess.getAccessId());
        order.setCount(1);
        order.setServiceCost(0.0);
        order.setPayerId(request.getPayerId());
        order.setCreateDate(new Date());
        order.setStatus(Enums.OrderStatusEnum.NO_PAYED.getValue());
        order.setOrderIp(request.getOrderIp());
        avsPayOrderService.save(order);
        Map<String, Object> result = new HashMap<>();
        result.put("amount", order.getRealAmount());
        result.put("url", access.getQuickUrl());
        result.put("orderNum", order.getOrderNum());
        return RestResponse.build(result);
    }

}
